package gold.digger;

import gold.utils.InputUtil;

import java.util.Arrays;
import java.util.Comparator;
import java.util.*;
import java.util.Map;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1233 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public List<String> removeSubfolders(String[] folder) {
            List<String> ans = new ArrayList<>();
            Arrays.sort(folder, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.length() - o2.length();
                }
            });
            Set<String> preMap = new HashSet<>();
            for (String dir : folder) {
                boolean curDelete = false;
                String[] splitDir = dir.split("/");
                StringBuilder dirAppend = new StringBuilder();
                for (String sub : splitDir) {
                    if (sub.length() <= 0) continue;
                    dirAppend.append("/").append(sub);
                    if (preMap.contains(dirAppend.toString())) {
                        curDelete = true;
                        break;
                    }
                }

                if (!curDelete) ans.add(dir);
                preMap.add(dir);
            }

            return ans;
        }
    }

    public void run() {
        System.out.println(new Solution().removeSubfolders(new String[]{"/a", "/a/b", "/c/d", "/c/d/e", "/c/f"}));
        System.out.println(new Solution().removeSubfolders(new String[]{"/a", "/a/b/c", "/a/b/d"}));
        System.out.println(new Solution().removeSubfolders(new String[]{"/a/b/c","/a/b/ca","/a/b/d"}));
    }

    public static void main(String[] args) throws Exception {
        LC1233 an = new LC1233();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
